/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.tracer.core;

import io.opentracing.SpanContext;
import io.opentracing.propagation.BinaryExtract;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

class ByteBufferSpanContext implements SpanContext {

    static final Charset CHARSET = Charset.forName("UTF-8");

    static final byte NO_ENTRY = 0, ENTRY = 1;

    private final ByteBuffer byteBuffer;

    public ByteBufferSpanContext(BinaryExtract carrier) {
        this.byteBuffer = carrier.extractionBuffer();
    }

    @Override
    public Iterable<Map.Entry<String, String>> baggageItems() {
        Map<String, String> baggageItems = new HashMap<String, String>();
        while (byteBuffer.get() == ENTRY) {
            byte[] key = new byte[byteBuffer.getInt()], value = new byte[byteBuffer.getInt()];
            byteBuffer.get(key);
            byteBuffer.get(value);
            baggageItems.put(new String(key, CHARSET), new String(value, CHARSET));
        }
        return baggageItems.entrySet();
    }

    @Override
    public String toSpanId() {
        return "";
    }

    @Override
    public String toTraceId() {
        return "";
    }
}
